import xml.dom.minidom
from xml.dom.minidom import Node

import random
from random import *
import string
from string import *

class XMLNode:
	def __init__(self, name):
		self._name = name
		self._children = []
		self._parent = None
		
	def __str__(self, spc=''):
		out = '\n' + spc + '<-- ' + self._name
		for i in dir(self):
			if i[0] != '_':
				out += "\n" + spc + "|  " + str(i) + ": " + str(getattr(self, i))
		for i in self._children:
			out += i.__str__(spc + '|  ')
		out += "\n" + spc + "-->"
		return out

def parseXML(node):
	n = XMLNode(node.tagName)
	for i in range(0, node.attributes.length):
		a = node.attributes.item(i)
		setattr(n, a.nodeName, a.nodeValue)
		
	for child in node.childNodes:
		#Add real child elements
		if child.nodeType == Node.ELEMENT_NODE:
			newc = parseXML(child)
			for c in newc:
				n._children.append(c)
				c._parent = n
				
		#Add text elements
		if child.nodeType == Node.TEXT_NODE:
			text = child.data
			text = text.replace("\t", "")
			if len(text) > 0:
				if text[-1] == "\n":
					text = text[0:-1]
				setattr(n, "text", text)
	return [n]
		
def cleanXML(node):
	mylist = node.childNodes
	for n in mylist:
		if n.nodeType == Node.COMMENT_NODE:
			mylist.remove(n)
		else:
			cleanXML(n)
	mylist = node.childNodes		
	for n in mylist:
		if n.nodeType == Node.TEXT_NODE:
			if len(n.data.split()) == 0:
				mylist.remove(n)
		else:
			cleanXML(n)
			
def getXML(filename):
	doc = xml.dom.minidom.parse(filename)
	cleanXML(doc)
	return doc